﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Xml.Linq;
using System.Text.RegularExpressions;
using System.Collections.ObjectModel;
using System.IO.IsolatedStorage;
using System.IO;
using System.Xml;
using Microsoft.Phone.Tasks;

namespace PhoneAppProject1
{
    public partial class Default : PhoneApplicationPage
    {
        #region Member
        private ObservableCollection<XMLPaser> itemSearch;
        #endregion

        public Default()
        {
            InitializeComponent();
        }

        private void PanoramaItem_Loaded(object sender, RoutedEventArgs e)
        {
            //WebClient webClientObj = new WebClient();
            //webClientObj.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClientObj_DownloadStringCompleted);
            //webClientObj.DownloadStringAsync(new Uri("http://rssfeeds.sanook.com/rss/feeds/sanook/game.hit.xml", UriKind.RelativeOrAbsolute));
            //webClientObj.DownloadStringAsync(new Uri("http://localhost/xmlTest.xml", UriKind.RelativeOrAbsolute));
        }

        void webClientObj_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                ListItem.SelectionChanged -= new SelectionChangedEventHandler(ListItem_SelectionChanged);
                ListItem.Visibility = System.Windows.Visibility.Collapsed;

                string str = e.Result.Replace("media:thumbnail", "XmllImage");
                XElement twitterObj = XElement.Parse(str);
                //XElement tempElementImage = twitterObj.Descendants(XName.Get("channel")).FirstOrDefault();
                //XElement tempElementItem = tempElementImage.Descendants(XName.Get("item")).FirstOrDefault();
                //XNamespace media = "media";
                //XElement tempElementImageURL = tempElementItem.Descendants(media + "thumbnail").FirstOrDefault();
                

                var Objv = from Obj in twitterObj.Descendants("channel")
                           from ObjIn in Obj.Descendants("item")
                           
                           select new XMLPaser
                           {
                               Title = ObjIn.Element("title").Value,
                               //Title = ObjIn.Element("title").Value.Replace("<![CDATA[", String.Empty).Replace("]]", String.Empty),
                               ImageURL = CheckImage(ObjIn),
                               CreateDate = Convert.ToDateTime(ObjIn.Element("pubDate").Value).ToString("dd, dddd MMMM yyyy"),
                               Message = this.CutDescription(Regex.Replace(ObjIn.Element("description").Value, @"<[^>]*>", String.Empty).ToString()),
                               Link = ObjIn.Element("guid").Value,
                               DetailAll = Regex.Replace(ObjIn.Element("description").Value, @"<[^>]*>", String.Empty)
                           };
                ListItem.ItemsSource = Objv;
                //myProgress.IsIndeterminate = !myProgress.IsIndeterminate;
                
                myProgress.Visibility = System.Windows.Visibility.Collapsed;
             
                ListItem.SelectionChanged += new SelectionChangedEventHandler(ListItem_SelectionChanged);
                ListItem.Visibility = System.Windows.Visibility.Visible;
               
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
                //ListItem.SelectionChanged -= new SelectionChangedEventHandler(ListItem_SelectionChanged);

            }
        }

        private string CheckImage(XElement ObjIn)
        {
            string ImageUrl = "";
            try
            {
                ImageUrl = ObjIn.Element("XmllImage").Attribute("url").Value;
                string[] image = ImageUrl.Split('.');

                if (image[image.Length - 1] == "gif")
                {
                    ImageUrl = "Nopicture.png";
                }
                else if (ImageUrl == "" || ImageUrl == null)
                {
                    ImageUrl = "Nopicture.png";
                }
            }
            catch
            {
                ImageUrl = "Nopicture.png";
            }
            return ImageUrl;
        }
        private string CutDescription(string Objstring)
        {
            if (Objstring.Length > 35)
            {
                Objstring = Objstring.Substring(0, 35) + " ...";
                return Objstring;
            }
            else
            {
                return Objstring+ " ...";
            }
          
        }
        private IsolatedStorageFile currentStore;
        public IsolatedStorageFile Store
        {
            get
            {
                this.currentStore = this.currentStore ?? IsolatedStorageFile.GetUserStoreForApplication();
                return this.currentStore;
            }
        }
        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            //myProgress.Visibility = System.Windows.Visibility.Visible;
            //myProgress.IsIndeterminate = !myProgress.IsIndeterminate;
            //WebClient webClientObj = new WebClient();
            //webClientObj.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClientObj_DownloadStringCompleted);
            ////webClientObj.DownloadStringAsync(new Uri("http://rssfeeds.sanook.com/rss/feeds/sanook/game.hit.xml", UriKind.RelativeOrAbsolute));
            ////webClientObj.DownloadStringAsync(new Uri("http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/football/rss.xml", UriKind.RelativeOrAbsolute));
            ////webClientObj.DownloadStringAsync(new Uri("http://drama-addict.com/feed/", UriKind.RelativeOrAbsolute));
            //webClientObj.DownloadStringAsync(new Uri("http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/other_sports/rss.xml", UriKind.RelativeOrAbsolute));
            //myProgress.Visibility = System.Windows.Visibility.Collapsed;
            this.GetDataXML();
            ListItemCat.SelectionChanged -= new SelectionChangedEventHandler(ListItemCat_SelectionChanged);
            ObservableCollection<XMLPaser> items = new ObservableCollection<XMLPaser>();
            XMLPaser xml = new XMLPaser();
            items.Add(new XMLPaser() { Title = "Cricket", Message = "The latest BBC Cricket news plus blogs, analysis, fixtures, scorecards, results, audio and video along with all the latest women’s cricket." });
            items.Add(new XMLPaser() { Title = "Football", Message = "The latest BBC Football news plus live scores, for all major UK and international leagues." });
            items.Add(new XMLPaser() { Title = "Golf", Message = "The latest BBC Golf news  on all the world’s major golf tournaments, along with video and audio." });
            items.Add(new XMLPaser() { Title = "Motorsport", Message = "The latest BBC Motorsport news: breaking news, comment and features on Formula 1, motorbikes and rallying plus MotoGP coverage." });
            items.Add(new XMLPaser() { Title = "Rugby League", Message = "The latest BBC Rugby League news plus scores, results, fixtures and tables. Super League match reports, blogs and analysis" });
            items.Add(new XMLPaser() { Title = "Snooker", Message = "The latest BBC Snooker news plus blogs, analysis, results and calendar along with video and audio." });
            items.Add(new XMLPaser() { Title = "Tennis", Message = "The latest BBC Tennis news on all the world’s major tennis tournaments, along with video and audio." });
            ListItemCat.ItemsSource = items;
			
            //ObservableCollection<XMLPaser> itemsSearch = new ObservableCollection<XMLPaser>();
            //XMLPaser xmlSearch = new XMLPaser();
            //itemsSearch.Add(new XMLPaser() { Title = "Cricket", 
            //                                 CreateDate = "9 Oct 2011",
            //                                 Message = "The latest BBC Cricket news plus blogs, analysis, fixtures, scorecards, results, audio and video along with all the latest women’s cricket." });
            //ListSearch.ItemsSource = itemsSearch;
			ListItemCat.SelectionChanged += new SelectionChangedEventHandler(ListItemCat_SelectionChanged);

            ///////////////////////////////////////////////////////////////////////////////////////////////////
            ListItemSaved.SelectionChanged -= new SelectionChangedEventHandler(ListItemSaved_SelectionChanged);
            try
            {
                IsolatedStorageSettings isoRead = IsolatedStorageSettings.ApplicationSettings;
                ObservableCollection<XMLPaser> itemsSaved = new ObservableCollection<XMLPaser>();

               IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
               IsolatedStorageFileStream isoStore = myIsolatedStorage.OpenFile("ItemSaved", FileMode.Open, FileAccess.Read);
               using (StreamReader reader = new StreamReader(isoStore))
               {
                   while (!reader.EndOfStream)
                   {
                       itemsSaved.Add(new XMLPaser {
                           Title = reader.ReadLine(),
                           ImageURL = reader.ReadLine(),
                           Link = reader.ReadLine(),
                           Message = CutDescription(reader.ReadLine()),
                           CreateDate = reader.ReadLine(),
                           DetailAll = reader.ReadLine()
                                                    });
                       //string title = reader.ReadLine();
                       //string ImgURL = reader.ReadLine();
                       //string str = reader.ReadLine(); 
                       //string str1 = reader.ReadLine();
                       //string str2 = reader.ReadLine();
                       //string str4 = reader.ReadLine();
                   }
                   reader.Close();             
               }
         
               ListItemSaved.ItemsSource = itemsSaved;
            }
            catch(Exception err)
            {

            }
            ListItemSaved.SelectionChanged += new SelectionChangedEventHandler(ListItemSaved_SelectionChanged);
        }

        private void PhoneApplicationPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (MessageBox.Show("Are you want to Exit ??", "Exit", MessageBoxButton.OKCancel) != MessageBoxResult.OK)
            {
                e.Cancel = true;
            }
            else
            {
                new App().Exit += new EventHandler(Default_Exit);
                //throw new NotImplementedException("ExitApplication");
            }
        }

        void Default_Exit(object sender, EventArgs e)
        {
            
            //throw new NotImplementedException();
        }

        private void ListItemCat_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
        	// TODO: Add event handler implementation here.
            XMLPaser Objv = (XMLPaser)ListItemCat.SelectedValue;
            string URL = "";
            switch (Objv.Title)
            {
                case "Football" :
                    URL = "http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/football/rss.xml";
                    break;
                case "Cricket":
                    URL = "http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/cricket/rss.xml";
                    break;
                case "Golf":
                    URL = "http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/golf/rss.xml";
                    break;
                case "Motorsport":
                    URL = "http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/motorsport/rss.xml";
                    break;
                case "Tennis":
                    URL = "http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/tennis/rss.xml";
                    break;
                case "Snooker":
                    URL = "http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/other_sports/snooker/rss.xml";
                    break;
                case "Rugby League":
                    URL = "http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/rugby_league/rss.xml";
                    break;


                default:
                    break;
            }

            NavigationService.Navigate(new Uri("/Detail_News.xaml?URL=" + URL + "&Title="+Objv.Title+"", UriKind.RelativeOrAbsolute));
            //MessageBox.Show(Objv.Title);
        }

        private void ListItem_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
        	// TODO: Add event handler implementation here.
            XMLPaser Objv = (XMLPaser)ListItem.SelectedValue;

            string URL = Objv.Link;
            NavigationService.Navigate(new Uri("/SNews_Detail.xaml?URL= " + Objv.Link + 
                                               "&Message=" + Objv.DetailAll + ""+
                                               "&Title=" + Objv.Title + ""+
                                               "&CreateDate=" + Objv.CreateDate + ""+
                                                "&ImgURL=" + Objv.ImageURL + "",
                                                UriKind.RelativeOrAbsolute));
        }

        private void btnRefresh_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            ListItem.SelectionChanged -= new SelectionChangedEventHandler(ListItem_SelectionChanged);
            ListItem.ItemsSource = null;
            this.GetDataXML();
        	// TODO: Add event handler implementation here.
        }

        private void GetDataXML()
        {
            myProgress.Visibility = System.Windows.Visibility.Visible;
            myProgress.IsIndeterminate = !myProgress.IsIndeterminate;
            WebClient webClientObj = new WebClient();
            webClientObj.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClientObj_DownloadStringCompleted);
            webClientObj.DownloadStringAsync(new Uri("http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/other_sports/rss.xml", UriKind.RelativeOrAbsolute));
        }
        private void SearchDataXML(string URL)
        {
            ListSearch.Visibility = System.Windows.Visibility.Collapsed;
            ProgessSearch.Visibility = System.Windows.Visibility.Visible;
           
            WebClient webClientObj = new WebClient();
            webClientObj.DownloadStringCompleted +=new DownloadStringCompletedEventHandler(SearchwebClientObj_DownloadStringCompleted);
            webClientObj.DownloadStringAsync(new Uri(URL, UriKind.RelativeOrAbsolute));
        }
        private void ListItemSaved_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
        	// TODO: Add event handler implementation here.
            XMLPaser Objv = (XMLPaser)ListItemSaved.SelectedValue;

            string URL = Objv.Link;
            NavigationService.Navigate(new Uri("/SNews_Detail.xaml?URL= " + Objv.Link + 
                                               "&Message=" + Objv.DetailAll + ""+
                                               "&Title=" + Objv.Title + ""+
                                               "&CreateDate=" + Objv.CreateDate + ""+
                                                "&ImgURL=" + Objv.ImageURL + "",
                                                UriKind.RelativeOrAbsolute));
        }

        private void btnSerachDef_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (txtSearch.Text.Trim() != "")
            {
                itemSearch = new ObservableCollection<XMLPaser>();
                SearchDataXML("http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/other_sports/rss.xml");
                SearchDataXML("http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/football/rss.xml");
                SearchDataXML("http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/golf/rss.xml");
                SearchDataXML("http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/cricket/rss.xml");
                SearchDataXML("http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/motorsport/rss.xml");
                SearchDataXML("http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/tennis/rss.xml");
                SearchDataXML("http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/other_sports/snooker/rss.xml");
                SearchDataXML("http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/rugby_league/rss.xml");
          
            }
            else
            {
                ListSearch.ItemsSource = null;
            }
        }

        void SearchwebClientObj_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            ListSearch.SelectionChanged -= new SelectionChangedEventHandler(ListSearch_SelectionChanged);
            ListSearch.Visibility = System.Windows.Visibility.Collapsed;

            string str = e.Result.Replace("media:thumbnail", "XmllImage");
            XElement twitterObj = XElement.Parse(str);
            foreach (XElement Obj in twitterObj.Descendants("channel")){
                foreach (XElement ObjIn in Obj.Descendants("item"))
                {
                    if (itemSearch.Count < 20)
                    {
                        string strValue = ObjIn.Element("description").Value;
                        int CountSearch = strValue.IndexOf(txtSearch.Text);
                        if (CountSearch > -1)
                        {
                            //Do sonething
                            string title = ObjIn.Element("title").Value;
                            itemSearch.Add(new XMLPaser()
                            {
                                Title = title,
                                Message = this.CutDescriptionSearch(Regex.Replace(strValue, @"<[^>]*>", String.Empty).ToString()),
                                ImageURL = CheckImage(ObjIn),
                                DetailAll = Regex.Replace(ObjIn.Element("description").Value, @"<[^>]*>", String.Empty),
                                Link = ObjIn.Element("guid").Value,
                                CreateDateSearch = Convert.ToDateTime(ObjIn.Element("pubDate").Value).ToString("dd MMM yyyy"),
                                CreateDate = Convert.ToDateTime(ObjIn.Element("pubDate").Value).ToString("dd dddd MMMM yyyy")

                            });
                        }
                        else
                        {
                            continue;
                        }
                    }
                }
            }
            //ProgessSearch.IsIndeterminate = !myProgress.IsIndeterminate;
            ProgessSearch.Visibility = System.Windows.Visibility.Collapsed;
            if (itemSearch.Count == 0)
            {
                //itemSearch.Clear();
                //itemSearch.Add(new XMLPaser()
                //{
                //    Title = "NOT FOUND"
                //});
                //ListSearch.ItemsSource = itemSearch;
                txtResultNo.Visibility = System.Windows.Visibility.Visible;

            }
            else if (itemSearch.Count > 0)
            {
                txtResultNo.Visibility = System.Windows.Visibility.Collapsed;
            }
            ListSearch.ItemsSource = itemSearch;
            ListSearch.Visibility = System.Windows.Visibility.Visible;
            ListSearch.SelectionChanged += new SelectionChangedEventHandler(ListSearch_SelectionChanged);
        }
        private string CutDescriptionSearch(string Objstring)
        {
            if (Objstring.Length > 70)
            {
                Objstring = Objstring.Substring(0, 70) + " ...";
                return Objstring;
            }
            else
            {
                return Objstring + " ...";
            }

        }
        private void txtSearch_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
        	// TODO: Add event handler implementation here.
			if (txtSearch.Text.Trim() != "")
            {
                itemSearch = new ObservableCollection<XMLPaser>();
                SearchDataXML("http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/other_sports/rss.xml");
                SearchDataXML("http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/football/rss.xml");
                SearchDataXML("http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/golf/rss.xml");
                SearchDataXML("http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/cricket/rss.xml");
                SearchDataXML("http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/motorsport/rss.xml");
                SearchDataXML("http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/tennis/rss.xml");
                SearchDataXML("http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/other_sports/snooker/rss.xml");
                SearchDataXML("http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/rugby_league/rss.xml");
               
                //else
                //{
                //    ListSearch.ItemsSource = itemSearch;
                //}
            }
            else
            {
                ListSearch.ItemsSource = null;
            }

        }

        private void ListSearch_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
        	// TODO: Add event handler implementation here.
            XMLPaser Objv = (XMLPaser)ListSearch.SelectedValue;

            string URL = Objv.Link;
            NavigationService.Navigate(new Uri("/SNews_Detail.xaml?URL= " + Objv.Link +
                                               "&Message=" + Objv.DetailAll + "" +
                                               "&Title=" + Objv.Title + "" +
                                               "&CreateDate=" + Objv.CreateDate + "" +
                                                "&ImgURL=" + Objv.ImageURL + "",
                                                UriKind.RelativeOrAbsolute));
        }

        private void btnBBCSNews_Click(object sender, System.Windows.RoutedEventArgs e)
        {
        	// TODO: Add event handler implementation here.
            WebBrowserTask webbrowser = new WebBrowserTask();
            webbrowser.URL = "http://news.bbc.co.uk/sport";
            webbrowser.Show();
        }
    }
}
